package com.atguigu.realtime.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.common.Constant;
import redis.clients.jedis.Jedis;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2022/2/12 15:19
 */
public class DimUtil {
    public static JSONObject readDimFromPhoenix(Connection conn, String tableName, Long id) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {
        String sql = "select * from " + tableName + " where id=?";
        
        Object[] args = {id.toString()};  // 存储给占位符赋值的数据
        
        // 返回值为什么是List集合?  查询语句, 查询的结果一般是多行, 每行封装一个对象, 多个对象放入到List集合
        List<JSONObject> dim = JdbcUtil.queryList(conn, sql, args, JSONObject.class);
        
        return dim.get(0);
    }
    
    public static JSONObject readDim(Jedis redisClient,
                                     Connection phoenixConn,
                                     String tableName,
                                     Long id) throws InvocationTargetException, SQLException, InstantiationException, IllegalAccessException {
        /*
        读取维度数据:
         1. 先从缓存读
         2. 如果缓存有, 则直接把结果返回
         3. 如果缓存没有, 则从Phoenix查询, 再把这个条维度存入到缓存, 把结果返回
         */
        JSONObject dim = readDimFromRedis(redisClient, tableName, id);
        if (dim == null) {
            System.out.println("从Phoenix读取数据: " + tableName + "   " + id);
            
            // 从Phoenix读取
            dim = readDimFromPhoenix(phoenixConn, tableName, id);
            // 把维度数据写入到缓存(redis)
            write2Redis(redisClient, tableName, id, dim);
        } else {
            System.out.println("从redis读取数据: " + tableName + "   " + id);
        }
        
        return dim;
    }
    
    private static void write2Redis(Jedis redisClient, String tableName, Long id, JSONObject dim) {
        // string
        // key:   dim_user_info:1   value:   json格式字符串      设置过期时间
        String key = tableName + ":" + id;
        String value = dim.toJSONString();
        
       /* redisClient.set(key, value);
        redisClient.expire(key, 3 * 24 * 60 * 60);  // 给key设置 3天的过期时间*/
        redisClient.setex(key, Constant.DIM_CACHE_TIMEOUT, value);
    }
    
    private static JSONObject readDimFromRedis(Jedis redisClient, String tableName, Long id) {
        String key = tableName + ":" + id;
        String value = redisClient.get(key);
        
        if (value != null) {  //如果key不存在, 则value是null
            redisClient.expire(key, Constant.DIM_CACHE_TIMEOUT);
            return JSON.parseObject(value);
        }
        // 如果一个缓存被使用了, 过期时间应该重新计算
        return null;
    }
    
}
/*
redis-server /etc/redis.conf
 */